<!--
  highcharts 仪表盘
-->

<template>
  <div :class="'h-gauge-wrap ' + wrapId" :id="wrapId" :ref="wrapId" :style="{ height: height, width: width }">
    <div :id="id" :ref="id" :class="'chart ' + className" />
    <div class="right-menu-wrap" ref="rightMenu">
      <slot name="right-menu"></slot>
    </div>
  </div>
</template>
<script>
import HighCharts from 'highcharts'
import { isFunction, merge, isEmpty } from 'lodash'
import config from '@/config'
// 图标跟随视窗变化而变化
import chartResize from '@/mixins/chartResize'
// highcharts 包裹框变化时，图表重新渲染
import chartDomeResize from '@/mixins/chartDomeResize'

export default {
  mixins: [chartResize, chartDomeResize],
  props: {
    id: {
      type: String,
      default: 'h-gauge'
    },
    className: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    chartData: {
      type: Object,
      default: null
    },
    fetchData: {
      type: Function
    },
    defaultOptions: {
      type: Object,
      default: () => ({})
    },
    shrink: {
      type: Boolean
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    wrapId() {
      return this.id + '-chart'
    }
  },
  mounted() {
    this.initChart()
    if (isFunction(this.fetchData)) {
      this.getChartData()
    }
    // 图表渲染前数据就已存在
    if (!isEmpty(this.chartData)) {
      this.chartRest()
    }
  },
  watch: {
    chartData: {
      handler() {
        this.chart.hideLoading()
        this.chartRest()
      },
      deep: true
    },
    /**
     * desc: 页面收缩时，执行图表重新渲染
     * param {type}
     * return:
     */
    shrink() {
      this.resize()
    }
  },
  beforeDestroy() {
    const { chart } = this
    if (chart) {
      chart.destroy()
      this.chart = null
    }
  },
  methods: {
    /**
     * 获取柱状图数据
     * @return {[type]} [description]
     */
    getChartData() {
      this.chart.showLoading('图表生成中...')
      this.fetchData()
    },
    /**
     * desc: 初始化图标
     * param {type}
     * return:
     */
    initChart() {
      const { chart } = this
      let currentChart = ''
      if (chart) {
        currentChart = chart
      } else {
        currentChart = HighCharts.chart(this.id, merge({}, config.hchartsDefaultOptions, this.defaultOptions))
      }
      this.chart = currentChart
    },
    /**
     * desc: 图标渲染
     * param {type}
     * return:
     */
    chartRest() {
      this.chart.update(this.chartData)
    },
    resize() {
      this.chart.reflow()
    }
  }
}
</script>
<style lang="less">
.h-gauge-wrap {
  .chart {
    width: 100%;
    height: 100%;
  }
}
</style>
